package demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DatabaseDemo01 {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/test2211?serverTimezone=GMT&useSSL=false";
            String username = "root";
            String password = "123456";
            Connection connection = DriverManager.getConnection(url, username, password);
            connection.setAutoCommit(false); // 开启事务,将自动事务提交改为手动提交

            // 添加数据
            /*String sql = "insert into tb_user(name, address, password) values (?, ?, ?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setString(1,"赵六");
            preparedStatement.setString(2,"湖北咸宁");
            preparedStatement.setString(3,"999888");
            int rows = preparedStatement.executeUpdate();
            System.out.println("影响了数据库表" + rows + "条数据");*/


            // 修改数据
            String sql1 = "update tb_user set salary = salary -  ? where id = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql1);

            preparedStatement.setDouble(1,3000.00);
            preparedStatement.setInt(2,3); // 后面的3表示id为3的那条数据
            int rows = preparedStatement.executeUpdate();


            String sql2 = "update tb_user set salary = salary +  ? where id = ?";
            preparedStatement = connection.prepareStatement(sql2);

            preparedStatement.setDouble(1,3000.00);
            preparedStatement.setInt(2,2); // 后面的2表示id为2的那条数据
            rows += preparedStatement.executeUpdate();




            connection.commit(); // 提交事务（所有操作完成之后）

            System.out.println("影响了数据库表" + rows + "条数据");

            preparedStatement.close();
            connection.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
